package com.zjut.multithreading.service;

import com.zjut.multithreading.dao.TimerTaskDao;
import com.zjut.multithreading.pojo.Ping;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Service
public class TimerTaskService {

    @Autowired
    private TimerTaskDao timerTaskDao;

    @Autowired
    private MongoTemplate mongoTemplate;

    public void doPing(String date, String time, String hour){
        final int N_THREADS = 500; // 线程池大小
        final int N_PINGS = 1000; // ping 数量
        //获取所有要ping的设备ip
        //List<String> ipAddressList = multithreadingMapper.getAllIpAddress();
        ExecutorService executorService = Executors.newFixedThreadPool(N_THREADS);
        List<Future<Document>> futures = new ArrayList<>();
        for (int i = 0; i < N_PINGS; i++) {
            String ipAddress = "192.168.1." + i;
            Callable<Document> ping = new Ping(ipAddress);
            Future<Document> future = executorService.submit(ping);
            futures.add(future);
        }

        executorService.shutdown();

        while (!executorService.isTerminated()) {
            // 等待所有任务执行完毕
        }

        int i = 0;
        for (Future<Document> future : futures) {
            try {
                Document doc = future.get();
                doc.put("checkDate", date);
                doc.put("checkTime", time);
                doc.put("checkHour", hour);
                mongoTemplate.insert(doc,"deviceStatusRealtimeStatistic");
                System.out.println(doc);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
